package com.cw.lang.common.mapper.helper;

import java.util.Set;

import org.apache.ibatis.type.JdbcType;

import tk.mybatis.mapper.annotation.Version;
import tk.mybatis.mapper.entity.EntityColumn;
import tk.mybatis.mapper.mapperhelper.EntityHelper;
import tk.mybatis.mapper.version.VersionException;

/**
 * Description: SqlHelper.java
 *
 * Created on 2018年01月05日
 *
 * @author chenw
 * @version 1.0
 * @since v1.0
 */
public final class SqlHelper extends tk.mybatis.mapper.mapperhelper.SqlHelper {

    /**
     * 私有构造函数
     */
    private SqlHelper() {}

    /**
     * example支持查询指定列时
     *
     * @param entityClass model类
     * @return sql语句
     */
    public static String exampleSelectColumnsWithoutBlob(Class<?> entityClass) {
        // 不支持指定列的时候查询全部列
        return "<choose>" + "<when test=\"@tk.mybatis.mapper.util.OGNL@hasSelectColumns(_parameter)\">"
            + "<foreach collection=\"_parameter.selectColumns\" item=\"selectColumn\" separator=\",\">"
            + "${selectColumn}" + "</foreach>" + "</when>" + "<otherwise>" + getAllColumnsWithoutBlob(entityClass)
            + "</otherwise>" + "</choose>";
    }

    /**
     * 获取所有非blob查询列，如id,name,code...
     *
     * @param entityClass model类
     * @return sql语句
     */
    public static String getAllColumnsWithoutBlob(Class<?> entityClass) {
        Set<EntityColumn> columnList = EntityHelper.getColumns(entityClass);
        StringBuilder sql = new StringBuilder();
        for (EntityColumn entityColumn : columnList) {
            if (JdbcType.BINARY.equals(entityColumn.getJdbcType()) || JdbcType.BLOB.equals(entityColumn.getJdbcType())
                || JdbcType.CLOB.equals(entityColumn.getJdbcType()) || JdbcType.LONGNVARCHAR.equals(
                entityColumn.getJdbcType()) || JdbcType.LONGVARBINARY.equals(entityColumn.getJdbcType())
                || JdbcType.LONGVARCHAR.equals(entityColumn.getJdbcType()) || JdbcType.NCLOB.equals(
                entityColumn.getJdbcType()) || JdbcType.VARBINARY.equals(entityColumn.getJdbcType())) {
                continue;
            }
            sql.append(entityColumn.getColumn())
                .append(",");
        }
        return sql.substring(0, sql.length() - 1);
    }

    /**
     * update list set列
     *
     * @param entityClass 对象实体
     * @param notNull 是否判断!=null
     * @param notEmpty 是否判断String类型!=''
     * @return set sql
     */
    public static String updateSetColumnsForList(Class<?> entityClass, String prefix, boolean notNull,
        boolean notEmpty) {
        StringBuilder sql = new StringBuilder();
        sql.append("<set>");
        //获取全部列
        Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass);
        //对乐观锁的支持，一个表中仅支持一个带@Version的字段
        EntityColumn versionColumn = null;
        for (EntityColumn column : columnSet) {
            if (column.getEntityField()
                .isAnnotationPresent(Version.class)) {
                if (versionColumn != null) {
                    throw new VersionException(
                        entityClass.getCanonicalName() + " 中包含多个带有 @Version 注解的字段，一个类中只能存在一个带有 @Version 注解的字段!");
                }
                versionColumn = column;
            }
            //当某个列有主键策略时，不需要考虑他的属性是否为空，因为如果为空，一定会根据主键策略给他生成一个值
            if (!column.isId() && column.isUpdatable()) {
                if (column == versionColumn) {
                    Version version = versionColumn.getEntityField()
                        .getAnnotation(Version.class);
                    String versionClass = version.nextVersion()
                        .getCanonicalName();
                    //version = ${@tk.mybatis.mapper.version@nextVersionClass("versionClass", version)}
                    sql.append(column.getColumn())
                        .append(" = ${@tk.mybatis.mapper.version.VersionUtil@nextVersion(")
                        .append("@")
                        .append(versionClass)
                        .append("@class, ")
                        .append("#{")
                        .append(prefix)
                        .append(".")
                        .append(column.getProperty())
                        .append("})},");
                    // String s
                    //     = "version = ${@tk.mybatis.mapper.version.VersionUtil@nextVersion(@tk.mybatis.mapper.version.DefaultNextVersion@class, #{record.version})},";
                } else if (notNull) {
                    sql.append(getIfNotNull(prefix, column, column.getColumnEqualsHolder(prefix) + ",", notEmpty));
                } else {
                    sql.append(column.getColumnEqualsHolder(prefix))
                        .append(",");
                }
            } else if (column.isId() && column.isUpdatable()) {
                //set id = id,
                sql.append(column.getColumn())
                    .append(" = ")
                    .append(column.getColumn())
                    .append(",");
            }
        }
        sql.append("</set>");
        return sql.toString();
    }

    /**
     * where主键条件
     *
     * @param entityClass 实体
     * @param prefix 前缀
     * @param useVersion 是否乐观锁
     * @return sql
     */
    public static String wherePKColumnsWithPrefix(Class<?> entityClass, String prefix, boolean useVersion) {
        StringBuilder sql = new StringBuilder();
        sql.append("<where>");
        //获取全部列
        Set<EntityColumn> columnSet = EntityHelper.getPKColumns(entityClass);
        //当某个列有主键策略时，不需要考虑他的属性是否为空，因为如果为空，一定会根据主键策略给他生成一个值
        for (EntityColumn column : columnSet) {
            sql.append(" AND ")
                .append(column.getColumnEqualsHolder(prefix));
        }
        if (useVersion) {
            sql.append(whereVersionWithPrefix(entityClass, prefix));
        }
        sql.append("</where>");
        return sql.toString();
    }

    /**
     * 乐观锁字段条件
     *
     * @param entityClass 实体
     * @param prefix 前缀
     * @return sql
     */
    private static String whereVersionWithPrefix(Class<?> entityClass, String prefix) {
        Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass);
        boolean hasVersion = false;
        String result = "";
        for (EntityColumn column : columnSet) {
            if (column.getEntityField()
                .isAnnotationPresent(Version.class)) {
                if (hasVersion) {
                    throw new VersionException(
                        entityClass.getCanonicalName() + " 中包含多个带有 @Version 注解的字段，一个类中只能存在一个带有 @Version 注解的字段!");
                }
                hasVersion = true;
                result = " AND " + column.getColumnEqualsHolder(prefix);
            }
        }
        return result;
    }
}
